package sf.jaxb;


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import sf.jaxb.model.Book;
import sf.jaxb.model.Bookstore;

public class BookMain
{

  private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

  public static void main(final String[] args)
    throws JAXBException, IOException
  {

    final List<Book> bookList = new ArrayList<Book>();

    // create books
    final Book book1 = new Book();
    book1.setIsbn("978-0060554736");
    book1.setName("The Game");
    book1.setAuthor("Neil Strauss");
    book1.setPublisher("Harpercollins");
    bookList.add(book1);

    final Book book2 = new Book();
    book2.setIsbn("978-3832180577");
    book2.setName("Feuchtgebiete");
    book2.setAuthor("Charlotte Roche");
    book2.setPublisher("Dumont Buchverlag");
    bookList.add(book2);
    
    final Book book3 = new Book();
    book3.setIsbn("978-3832180577");
    book3.setName("Tale of Two Cities");
    book3.setAuthor("Charles Dickens");
    bookList.add(book3);
    
    // create bookstore, assigning book
    final Bookstore bookstore = new Bookstore();
    bookstore.setName("Fraport Bookstore");
    bookstore.setLocation("Frankfurt Airport");
    bookstore.setBookList(bookList);

    // create JAXB context and instantiate marshaller
    final JAXBContext context = JAXBContext.newInstance(Bookstore.class);
    final Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(bookstore, System.out);

    Writer w = null;
    try
    {
      w = new FileWriter(BOOKSTORE_XML);
      m.marshal(bookstore, w);
    }
    finally
    {
      try
      {
        w.close();
      }
      catch (final Exception e)
      {
      }
    }

    // get variables from our xml file, created before
    System.out.println();
    System.out.println("Output from our XML File: ");
    final Unmarshaller um = context.createUnmarshaller();
    final Bookstore bookstore2 = (Bookstore) um
      .unmarshal(new FileReader(BOOKSTORE_XML));

    for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++)
    {
      System.out.println("Book " + (i + 1) + ": "
                         + bookstore2.getBooksList().get(i));
    }

  }

}
